﻿using Common.Library;
using Common.Model;
using Container.Library;
using Dapper.Library;
using DevOps.Model;
using Serialize.Library;
using System.Collections.Generic;

namespace DevOps.Logic
{
    /// <summary>
    /// 应用管理逻辑类
    /// </summary>
    public class SafeApplicationInfoServiceImpl : OperationLogicImpl, ISafeApplicationInfoService
    {
        #region 应用基础管理

        #region 查询
        /// <summary>
        /// 根据关键字 分页获取应用列表
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<SafeApplicationInfoResponse>> LoadSysApplicationList(ParametersInfo<string> inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<SafeApplicationInfoResponse>>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = con.QuerySet<SafeApplicationInfoEntity>().Where(a => a.is_deleted == false);
                if (inputInfo.parameters.IsNotNullOrEmpty())
                {
                    result.Where(a => a.applicatian_name.Contains(inputInfo.parameters) || a.accountid.Contains(inputInfo.parameters));
                }

                #region 排序
                if (inputInfo.field.IsNullOrEmpty())
                {
                    inputInfo.field = " applicatian_type";
                }
                if (inputInfo.order.IsNullOrEmpty())
                {
                    inputInfo.order = " asc";
                }
                if (inputInfo.order.ToLower() == "asc")
                {
                    result.OrderBy(inputInfo.field);
                }
                else
                {
                    result.OrderByDescing(inputInfo.field);
                }
                #endregion

                var listInfo = result.PageList(inputInfo.page, inputInfo.limit);

                if (listInfo.Items.Count > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo.Items.MapToList<SafeApplicationInfoResponse>();
                    resultInfo.Count = listInfo.Total;
                }
                else
                {
                    resultInfo.Data = new List<SafeApplicationInfoResponse>();
                    resultInfo.Msg = "无对应信息！";
                }
            }

            return resultInfo;
        }

        /// <summary>
        /// 获取应用列表下拉框信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<EnumToSelectItem>> LoadSelectList()
        {
            var resultInfo = new ResultJsonInfo<List<EnumToSelectItem>>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var listInfo = con.QuerySet<SafeApplicationInfoEntity>().Where(p =>p.is_deleted==false).ToList();

                if (listInfo.Count > 0)
                {
                    List<EnumToSelectItem> selectList = new List<EnumToSelectItem>();
                    foreach (var item in listInfo)
                    {
                        selectList.Add(new EnumToSelectItem()
                        {
                            Value = item.id,
                            Text = item.applicatian_name
                        });
                    }
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = selectList;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 获取应用列表Select树状数据
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<SelectListInfo>> LoadTreeList()
        {

            var resultInfo = new ResultJsonInfo<List<SelectListInfo>>();

            List<SelectListInfo> listInfo = new List<SelectListInfo>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var applicationListInfo = con.QuerySet<SafeApplicationInfoEntity>().Where(p => p.is_deleted == false).ToList();

                if (applicationListInfo.Count > 0)
                {
                    foreach (var item in applicationListInfo)
                    {
                        SelectListInfo departmentInfo = new SelectListInfo()
                        {
                            value = item.id,
                            name = item.applicatian_name,
                            children = null
                        };
                        listInfo.Add(departmentInfo);
                    }

                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo;
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "获取应用列表失败！";
                }
            }
            return resultInfo;
        }


        /// <summary>
        /// 获取应用类型Select列表信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<EnumToSelectItem>> LoadApplicationTypeList()
        {

            var resultInfo = new ResultJsonInfo<List<EnumToSelectItem>>();
            resultInfo.Data = EnumToSelectItem.GetEnumDescriptionList(typeof(ApplicationType), true);
            resultInfo.Code = ActionCodes.Success;
            resultInfo.Msg = "获取成功！";

            return resultInfo;
        }



        #endregion

        #region 修改
        /// <summary>
        /// 修改一个应用
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> ModifySysApplication(SafeApplicationInfoModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var user = GetLoginUserInfo();

                var sysApplication = con.QuerySet<SafeApplicationInfoEntity>().Where(p => p.id == inputInfo.id).Get();
                if (sysApplication != null)
                {
                    sysApplication.accountid = inputInfo.accountid;
                    sysApplication.applicatian_name = inputInfo.applicatian_name;
                    sysApplication.applicatian_type = inputInfo.applicatian_type;
                    sysApplication.appsecret = inputInfo.appsecret;
                    sysApplication.unionid = inputInfo.unionid;


                    var result = con.CommandSet<SafeApplicationInfoEntity>().Update(sysApplication);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "操作成功！";
                        AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.Application, $"修改应用成功，修改应用信息：{JsonHelper.ToJson(sysApplication)}");
                    }
                    else
                    {
                        resultInfo.Msg = $"应用{JsonHelper.ToJson(sysApplication)}修改失败！";
                    }
                }
                else
                {
                    resultInfo.Code = ActionCodes.ArgumentInvalid;
                    resultInfo.Msg = "ID无效！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 删除应用
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> DeleteSysApplication(List<string> applicationId)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var user = GetLoginUserInfo();
                var applist = applicationId.ToArray();
                var sysApplication = con.QuerySet<SafeApplicationInfoEntity>().Where(a => a.id.In(applist)).ToList();
                if (sysApplication.Count == 0)
                {
                    resultInfo.Code = ActionCodes.ArgumentInvalid;
                    resultInfo.Msg = "参数无效！";
                    return resultInfo;
                }
                sysApplication.ForEach(a => a.is_deleted = true);

                var result = con.CommandSet<SafeApplicationInfoEntity>().Update(sysApplication);
                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "删除应用成功！";
                    AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.Application, $"删除应用成功，删除应用信息：{JsonHelper.ToJson(sysApplication)}");
                }
                else
                {
                    resultInfo.Msg = "删除应用失败！";
                }
            }
            return resultInfo;
        }
        /// <summary>
        /// 禁用/启用应用
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> ForbiddenSysApplication(string applicationId)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var user = GetLoginUserInfo();
                var sysApplication = con.QuerySet<SafeApplicationInfoEntity>().Where(a => a.id == applicationId).Get();
                if (sysApplication == null)
                {
                    resultInfo.Code = ActionCodes.ArgumentInvalid;
                    resultInfo.Msg = "参数无效！";
                    return resultInfo;
                }
                if (sysApplication.is_valid)
                {
                    sysApplication.is_valid = false;
                }
                else
                {
                    sysApplication.is_valid = true;
                }

                var result = con.CommandSet<SafeApplicationInfoEntity>().Update(sysApplication);
                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "禁用/启用应用成功！";
                    AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.Application, $"禁用/启用应用成功，禁用/启用应用信息：{JsonHelper.ToJson(sysApplication)}");
                }
                else
                {
                    resultInfo.Msg = "禁用/启用应用失败！";
                }
            }
            return resultInfo;

        }
        #endregion

        #region 添加
        /// <summary>
        /// 新增一个应用
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> AddSysApplication(SafeApplicationInfoAddRequest addRequest)
        {

            var resultInfo = new ResultJsonInfo<int>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var user = GetLoginUserInfo();

                var appinfo = addRequest.MapTo<SafeApplicationInfoEntity>();

                var addlist = con.QuerySet<SafeApplicationInfoEntity>().Where(a => (a.accountid == addRequest.accountid || a.applicatian_name == addRequest.applicatian_name)&&a.is_deleted==false).ToList();
                if (addlist.Count > 0)
                {
                    resultInfo.Code = ActionCodes.InvalidOperation;
                    resultInfo.Msg = "应用名称或者应用登录名重复！";
                    return resultInfo;
                }
                var result = con.CommandSet<SafeApplicationInfoEntity>()
                     .Insert(appinfo);

                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "添加成功！";
                    AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.Application, $"添加了一个新的应用，新增应用信息：{JsonHelper.ToJson(addRequest)}");
                }
                else
                {
                    resultInfo.Code = ActionCodes.InvalidOperation;
                    resultInfo.Msg = "添加失败！";
                }
            }

            return resultInfo;
        }

        #endregion

        #endregion
    }
}
